<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="200px"
      v-loading="formLoading"
    >
      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="formData.orderNo" placeholder="请输入订单号" />
      </el-form-item>
      <el-form-item label="平台订单ID" prop="platformOrderId">
        <el-input v-model="formData.platformOrderId" placeholder="请输入平台订单ID" />
      </el-form-item>
      <el-form-item label="平台订单号" prop="platformOrderNo">
        <el-input v-model="formData.platformOrderNo" placeholder="请输入平台订单号" />
      </el-form-item>
      <el-form-item label="平台编号" prop="platformId">
        <el-input v-model="formData.platformId" placeholder="请输入平台编号" />
      </el-form-item>
      <el-form-item label="店铺编号" prop="storeId">
        <el-input v-model="formData.storeId" placeholder="请输入店铺编号" />
      </el-form-item>
      <el-form-item label="客户编号" prop="customerId">
        <el-input v-model="formData.customerId" placeholder="请输入客户编号" />
      </el-form-item>
      <el-form-item label="客户编号" prop="customerNo">
        <el-input v-model="formData.customerNo" placeholder="请输入客户编号" />
      </el-form-item>
      <el-form-item label="订单类型" prop="orderType">
        <el-select v-model="formData.orderType" placeholder="请选择订单类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_ORDER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单来源" prop="orderSource">
        <el-input v-model="formData.orderSource" placeholder="请输入订单来源" />
      </el-form-item>
      <el-form-item label="销售渠道" prop="salesChannel">
        <el-input v-model="formData.salesChannel" placeholder="请输入销售渠道" />
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-radio-group v-model="formData.orderStatus">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_ORDER_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="支付状态" prop="paymentStatus">
        <el-radio-group v-model="formData.paymentStatus">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_PAYMENT_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="履约状态" prop="fulfillmentStatus">
        <el-radio-group v-model="formData.fulfillmentStatus">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_FULFILLMENT_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="订单货币" prop="currencyCode">
        <el-input v-model="formData.currencyCode" placeholder="请输入订单货币" />
      </el-form-item>
      <el-form-item label="汇率" prop="exchangeRate">
        <el-input v-model="formData.exchangeRate" placeholder="请输入汇率" />
      </el-form-item>
      <el-form-item label="基础货币" prop="baseCurrency">
        <el-input v-model="formData.baseCurrency" placeholder="请输入基础货币" />
      </el-form-item>
      <el-form-item label="商品种类数" prop="itemCount">
        <el-input v-model="formData.itemCount" placeholder="请输入商品种类数" />
      </el-form-item>
      <el-form-item label="商品总数量" prop="totalQuantity">
        <el-input v-model="formData.totalQuantity" placeholder="请输入商品总数量" />
      </el-form-item>
      <el-form-item label="商品小计金额" prop="subtotalAmount">
        <el-input v-model="formData.subtotalAmount" placeholder="请输入商品小计金额" />
      </el-form-item>
      <el-form-item label="运费" prop="shippingAmount">
        <el-input v-model="formData.shippingAmount" placeholder="请输入运费" />
      </el-form-item>
      <el-form-item label="税费" prop="taxAmount">
        <el-input v-model="formData.taxAmount" placeholder="请输入税费" />
      </el-form-item>
      <el-form-item label="关税" prop="dutyAmount">
        <el-input v-model="formData.dutyAmount" placeholder="请输入关税" />
      </el-form-item>
      <el-form-item label="保险费" prop="insuranceAmount">
        <el-input v-model="formData.insuranceAmount" placeholder="请输入保险费" />
      </el-form-item>
      <el-form-item label="手续费" prop="handlingFee">
        <el-input v-model="formData.handlingFee" placeholder="请输入手续费" />
      </el-form-item>
      <el-form-item label="折扣金额" prop="discountAmount">
        <el-input v-model="formData.discountAmount" placeholder="请输入折扣金额" />
      </el-form-item>
      <el-form-item label="优惠券金额" prop="couponAmount">
        <el-input v-model="formData.couponAmount" placeholder="请输入优惠券金额" />
      </el-form-item>
      <el-form-item label="积分抵扣金额" prop="pointsAmount">
        <el-input v-model="formData.pointsAmount" placeholder="请输入积分抵扣金额" />
      </el-form-item>
      <el-form-item label="调整金额" prop="adjustmentAmount">
        <el-input v-model="formData.adjustmentAmount" placeholder="请输入调整金额" />
      </el-form-item>
      <el-form-item label="订单总金额" prop="totalAmount">
        <el-input v-model="formData.totalAmount" placeholder="请输入订单总金额" />
      </el-form-item>
      <el-form-item label="已支付金额" prop="paidAmount">
        <el-input v-model="formData.paidAmount" placeholder="请输入已支付金额" />
      </el-form-item>
      <el-form-item label="退款金额" prop="refundAmount">
        <el-input v-model="formData.refundAmount" placeholder="请输入退款金额" />
      </el-form-item>
      <el-form-item label="获得积分" prop="pointsEarned">
        <el-input v-model="formData.pointsEarned" placeholder="请输入获得积分" />
      </el-form-item>
      <el-form-item label="使用积分" prop="pointsUsed">
        <el-input v-model="formData.pointsUsed" placeholder="请输入使用积分" />
      </el-form-item>
      <el-form-item label="下单时间" prop="orderTime">
        <el-date-picker
          v-model="formData.orderTime"
          type="date"
          value-format="x"
          placeholder="选择下单时间"
        />
      </el-form-item>
      <el-form-item label="确认时间" prop="confirmTime">
        <el-date-picker
          v-model="formData.confirmTime"
          type="date"
          value-format="x"
          placeholder="选择确认时间"
        />
      </el-form-item>
      <el-form-item label="支付时间" prop="paymentTime">
        <el-date-picker
          v-model="formData.paymentTime"
          type="date"
          value-format="x"
          placeholder="选择支付时间"
        />
      </el-form-item>
      <el-form-item label="发货时间" prop="shipTime">
        <el-date-picker
          v-model="formData.shipTime"
          type="date"
          value-format="x"
          placeholder="选择发货时间"
        />
      </el-form-item>
      <el-form-item label="送达时间" prop="deliveryTime">
        <el-date-picker
          v-model="formData.deliveryTime"
          type="date"
          value-format="x"
          placeholder="选择送达时间"
        />
      </el-form-item>
      <el-form-item label="完成时间" prop="completeTime">
        <el-date-picker
          v-model="formData.completeTime"
          type="date"
          value-format="x"
          placeholder="选择完成时间"
        />
      </el-form-item>
      <el-form-item label="取消时间" prop="cancelTime">
        <el-date-picker
          v-model="formData.cancelTime"
          type="date"
          value-format="x"
          placeholder="选择取消时间"
        />
      </el-form-item>
      <el-form-item label="取消原因" prop="cancelReason">
        <el-input v-model="formData.cancelReason" placeholder="请输入取消原因" />
      </el-form-item>
      <el-form-item label="预计送达日期" prop="expectedDeliveryDate">
        <el-date-picker
          v-model="formData.expectedDeliveryDate"
          type="date"
          value-format="x"
          placeholder="选择预计送达日期"
        />
      </el-form-item>
      <el-form-item label="发货截止时间" prop="deliveryDeadline">
        <el-date-picker
          v-model="formData.deliveryDeadline"
          type="date"
          value-format="x"
          placeholder="选择发货截止时间"
        />
      </el-form-item>
      <el-form-item label="自动确认天数" prop="autoConfirmDays">
        <el-input v-model="formData.autoConfirmDays" placeholder="请输入自动确认天数" />
      </el-form-item>
      <el-form-item label="买家留言" prop="buyerMessage">
        <el-input v-model="formData.buyerMessage" placeholder="请输入买家留言" />
      </el-form-item>
      <el-form-item label="卖家备注" prop="sellerMessage">
        <el-input v-model="formData.sellerMessage" placeholder="请输入卖家备注" />
      </el-form-item>
      <el-form-item label="内部备注" prop="internalNotes">
        <el-input v-model="formData.internalNotes" placeholder="请输入内部备注" />
      </el-form-item>
      <el-form-item label="风险评分" prop="riskScore">
        <el-input v-model="formData.riskScore" placeholder="请输入风险评分" />
      </el-form-item>
      <el-form-item label="风险等级" prop="riskLevel">
        <el-select v-model="formData.riskLevel" placeholder="请选择风险等级">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_RISK_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="反欺诈检查状态" prop="fraudCheckStatus">
        <el-radio-group v-model="formData.fraudCheckStatus">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_FRAUD_CHECK_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否紧急订单" prop="isUrgent">
        <el-radio-group v-model="formData.isUrgent">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否礼品订单" prop="isGift">
        <el-radio-group v-model="formData.isGift">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="礼品留言" prop="giftMessage">
        <el-input v-model="formData.giftMessage" placeholder="请输入礼品留言" />
      </el-form-item>
      <el-form-item label="是否代发货" prop="isDropshipping">
        <el-radio-group v-model="formData.isDropshipping">
          <el-radio value="1">请选择字典生成</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="订单标签，逗号分隔" prop="tags">
        <el-input v-model="formData.tags" placeholder="请输入订单标签，逗号分隔" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { OrderMainApi, OrderMainVO } from '@/api/crossborder/ordermain'
import { DICT_TYPE, getIntDictOptions, getBoolDictOptions } from '@/utils/dict'

/** 跨境电商订单主 表单 */
defineOptions({ name: 'OrderMainForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  orderNo: undefined,
  platformOrderId: undefined,
  platformOrderNo: undefined,
  platformId: undefined,
  storeId: undefined,
  customerId: undefined,
  customerNo: undefined,
  orderType: undefined,
  orderSource: undefined,
  salesChannel: undefined,
  orderStatus: undefined,
  paymentStatus: undefined,
  fulfillmentStatus: undefined,
  currencyCode: undefined,
  exchangeRate: undefined,
  baseCurrency: undefined,
  itemCount: undefined,
  totalQuantity: undefined,
  subtotalAmount: undefined,
  shippingAmount: undefined,
  taxAmount: undefined,
  dutyAmount: undefined,
  insuranceAmount: undefined,
  handlingFee: undefined,
  discountAmount: undefined,
  couponAmount: undefined,
  pointsAmount: undefined,
  adjustmentAmount: undefined,
  totalAmount: undefined,
  paidAmount: undefined,
  refundAmount: undefined,
  pointsEarned: undefined,
  pointsUsed: undefined,
  orderTime: undefined,
  confirmTime: undefined,
  paymentTime: undefined,
  shipTime: undefined,
  deliveryTime: undefined,
  completeTime: undefined,
  cancelTime: undefined,
  cancelReason: undefined,
  expectedDeliveryDate: undefined,
  deliveryDeadline: undefined,
  autoConfirmDays: undefined,
  buyerMessage: undefined,
  sellerMessage: undefined,
  internalNotes: undefined,
  riskScore: undefined,
  riskLevel: undefined,
  fraudCheckStatus: undefined,
  isUrgent: undefined,
  isGift: undefined,
  giftMessage: undefined,
  isDropshipping: undefined,
  tags: undefined,
})
const formRules = reactive({
  orderNo: [{ required: true, message: '订单号不能为空', trigger: 'blur' }],
  customerId: [{ required: true, message: '客户编号不能为空', trigger: 'blur' }],
  customerNo: [{ required: true, message: '客户编号不能为空', trigger: 'blur' }],
  orderType: [{ required: true, message: '订单类型（1普通订单 2预售订单 3团购订单 4批发订单 5换货订单）不能为空', trigger: 'change' }],
  orderStatus: [{ required: true, message: '订单状态（10待确认 20待支付 30已支付 40备货中 50已发货 60已送达 70已完成 80已取消 90已退款）不能为空', trigger: 'blur' }],
  paymentStatus: [{ required: true, message: '支付状态（10未支付 20部分支付 30已支付 40支付失败 50已退款 60部分退款）不能为空', trigger: 'blur' }],
  fulfillmentStatus: [{ required: true, message: '履约状态（10待处理 20备货中 30已分配 40拣货中 50已拣货 60已打包 70已发货 80运输中 90已送达）不能为空', trigger: 'blur' }],
  currencyCode: [{ required: true, message: '订单货币不能为空', trigger: 'blur' }],
  exchangeRate: [{ required: true, message: '汇率不能为空', trigger: 'blur' }],
  itemCount: [{ required: true, message: '商品种类数不能为空', trigger: 'blur' }],
  totalQuantity: [{ required: true, message: '商品总数量不能为空', trigger: 'blur' }],
  subtotalAmount: [{ required: true, message: '商品小计金额不能为空', trigger: 'blur' }],
  shippingAmount: [{ required: true, message: '运费不能为空', trigger: 'blur' }],
  taxAmount: [{ required: true, message: '税费不能为空', trigger: 'blur' }],
  dutyAmount: [{ required: true, message: '关税不能为空', trigger: 'blur' }],
  insuranceAmount: [{ required: true, message: '保险费不能为空', trigger: 'blur' }],
  handlingFee: [{ required: true, message: '手续费不能为空', trigger: 'blur' }],
  discountAmount: [{ required: true, message: '折扣金额不能为空', trigger: 'blur' }],
  couponAmount: [{ required: true, message: '优惠券金额不能为空', trigger: 'blur' }],
  pointsAmount: [{ required: true, message: '积分抵扣金额不能为空', trigger: 'blur' }],
  adjustmentAmount: [{ required: true, message: '调整金额不能为空', trigger: 'blur' }],
  totalAmount: [{ required: true, message: '订单总金额不能为空', trigger: 'blur' }],
  paidAmount: [{ required: true, message: '已支付金额不能为空', trigger: 'blur' }],
  refundAmount: [{ required: true, message: '退款金额不能为空', trigger: 'blur' }],
  pointsEarned: [{ required: true, message: '获得积分不能为空', trigger: 'blur' }],
  pointsUsed: [{ required: true, message: '使用积分不能为空', trigger: 'blur' }],
  orderTime: [{ required: true, message: '下单时间不能为空', trigger: 'blur' }],
  isUrgent: [{ required: true, message: '是否紧急订单不能为空', trigger: 'blur' }],
  isGift: [{ required: true, message: '是否礼品订单不能为空', trigger: 'blur' }],
  isDropshipping: [{ required: true, message: '是否代发货不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OrderMainApi.getOrderMain(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OrderMainVO
    if (formType.value === 'create') {
      await OrderMainApi.createOrderMain(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrderMainApi.updateOrderMain(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    orderNo: undefined,
    platformOrderId: undefined,
    platformOrderNo: undefined,
    platformId: undefined,
    storeId: undefined,
    customerId: undefined,
    customerNo: undefined,
    orderType: undefined,
    orderSource: undefined,
    salesChannel: undefined,
    orderStatus: undefined,
    paymentStatus: undefined,
    fulfillmentStatus: undefined,
    currencyCode: undefined,
    exchangeRate: undefined,
    baseCurrency: undefined,
    itemCount: undefined,
    totalQuantity: undefined,
    subtotalAmount: undefined,
    shippingAmount: undefined,
    taxAmount: undefined,
    dutyAmount: undefined,
    insuranceAmount: undefined,
    handlingFee: undefined,
    discountAmount: undefined,
    couponAmount: undefined,
    pointsAmount: undefined,
    adjustmentAmount: undefined,
    totalAmount: undefined,
    paidAmount: undefined,
    refundAmount: undefined,
    pointsEarned: undefined,
    pointsUsed: undefined,
    orderTime: undefined,
    confirmTime: undefined,
    paymentTime: undefined,
    shipTime: undefined,
    deliveryTime: undefined,
    completeTime: undefined,
    cancelTime: undefined,
    cancelReason: undefined,
    expectedDeliveryDate: undefined,
    deliveryDeadline: undefined,
    autoConfirmDays: undefined,
    buyerMessage: undefined,
    sellerMessage: undefined,
    internalNotes: undefined,
    riskScore: undefined,
    riskLevel: undefined,
    fraudCheckStatus: undefined,
    isUrgent: undefined,
    isGift: undefined,
    giftMessage: undefined,
    isDropshipping: undefined,
    tags: undefined,
  }
  formRef.value?.resetFields()
}
</script>